package com.hongtu.supplychain.finance.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.hongtu.supplychain.finance.consumer.params.enums.EWeChatBackCode;
import com.hongtu.supplychain.finance.consumer.replyata.ReplyData;
import com.hongtu.supplychain.finance.util.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 授权拦截器，用于刷新授权时间
 *
 * @author chaiy
 * @create 2017-04-11 15:22
 */
public class AuthInterceptor implements HandlerInterceptor {

    private final static List<String> publicUrl = new ArrayList(Arrays.asList(new String[]{

    }));

    @Autowired
    private JedisPlugin jedisPlugin;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String reqUrl = httpServletRequest.getRequestURI();
        if(publicUrl.contains(reqUrl)) {
            return true;
        }else if(httpServletRequest.getHeader(MUtil.PUBLIC_LB) != null && httpServletRequest.getHeader(MUtil.PUBLIC_LB).equals("mobile")){  //手机APP
            return true;
        }
        String loginSession = httpServletRequest.getHeader(WXAuthUtil.PUBLIC_PARAM);
        if(StringUtils.isNotEmpty(loginSession)) {
            String key = String.format(WXAuthUtil.USER_KEY, loginSession);
            // 用户可能存在登录超过30分钟的情况(需要重新发起静默授权)
            if(!jedisPlugin.exists(key)) {
                loginTimeout(httpServletResponse, EWeChatBackCode.LOGIN_TIMEOUT_CODE);
                return false;
            }
            String values = jedisPlugin.get(key);
            jedisPlugin.set(key, values, WXAuthUtil.CACHE_INFO_TIME);
            UserLoginInfo info =  JSONObject.parseObject(values, UserLoginInfo.class);
            // 如果获取到的用户没有 且也不是登录或注册相关操作 则需要跳转到登录界面
            if(info.getUserId() == null && !MAuthInterceptor.excludeUrl.contains(reqUrl)) {
                loginTimeout(httpServletResponse, EWeChatBackCode.OFF_SITE_LOGIN_CODE);
                return false;
            }
            SessionThreadLocal.setSession(info);
            return true;
        }
        return false;
    }


    private void loginTimeout(HttpServletResponse httpServletResponse, EWeChatBackCode backCode) {
        try {
            ReplyData replyData = new ReplyData();
            replyData.setCode(backCode.getCode());
            replyData.setMsg(backCode.getTypeName());
            httpServletResponse.setContentType("text/html; charset=UTF-8");
            httpServletResponse.getWriter().print(JSONObject.toJSONString(replyData));
            httpServletResponse.getWriter().close();
        } catch (Exception e) {

        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {}
}
